package com.exercise.ThreadSynchronization.volatileMethod;

public class NonVolatileSingletonDemo {
    // 未使用volatile
    private static Singleton instance;

    static class Singleton {
        private String name; // 成员变量

        private Singleton() {
            // 模拟复杂初始化
            this.name = "Initialized";
            // 模拟耗时操作
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public String getName() {
            return name;
        }
    }

    public static Singleton getInstance() {
        if (instance == null) { // 第一次检查
            synchronized (NonVolatileSingletonDemo.class) {
                if (instance == null) { // 第二次检查
                    instance = new Singleton(); // 创建对象
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        Runnable task = () -> {
            Singleton singleton = getInstance();
            // 访问name字段
            System.out.println(Thread.currentThread().getName() + ": " + singleton.getName());
        };

        // 启动多个线程
        Thread[] threads = new Thread[10];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(task, "Thread-" + i);
            threads[i].start();
        }
    }
}
